package com.ltv.xiangqibook.web;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;
import com.ltv.xiangqibook.util.MD5Util;

public class XiangqiBookListener implements ServletContextListener {
	private static final Logger logger = Logger.getLogger(XiangqiBookListener.class.getCanonicalName());

    public void contextInitialized(ServletContextEvent event) {
    	try {
			XiangQiBookConfiguration.getInstance().loadConfiguration(XiangQiBookConfiguration.CONFIG_FILE_NAME);
		} catch (Exception e) {
			logger.severe("Error loading configuration: " + e.getMessage());
		}
    	
        // Initialize MessageService
        try {
			MessageService.getInstance().init();
		} catch (Exception e) {
			logger.severe("Error initializing MessageService: " + e.getMessage());
		}
    	
    	if (!XiangQiBookConfiguration.getInstance().isFirstLoad()) {
    		return;
    	}
    	
    	// Remove all old games
    	List<Key> keys = new ArrayList<Key>();
    	for (Entity entity : Game.getAllGames()) {
    		keys.add(entity.getKey());
    	}
    	Util.deleteEntity(keys);
    	
    	// Add new games
        try {
            File fXmlFile = new File("xml/" + XiangQiBookConfiguration.getInstance().getXmlVersion() + "/games.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("game");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    Game.createGame(
                            getTagValue("id", eElement),
                            getTagValue("location", eElement),
                            new Text(getTagValue("comment", eElement)));
                }
            }
        } catch (Exception e) {
        	logger.severe("Error adding new games: " + e.getMessage());
        }
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        if (nValue != null) {
            return nValue.getNodeValue();
        }
        return "";
    }
    public void contextDestroyed(ServletContextEvent event) {
        // App Engine does not currently invoke this method.
    }
}